import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { AppPaginationComponent, PaginationModel } from "../../../../../widgets/pagination/pagination.component";
import { environment } from "../../../../../../environments/environment";
import * as _ from "lodash";
import { Util } from '../../../../../common/util';
import { RemindService } from './remind.service';
import { DataService } from 'app/services/data.service';
import { SearchRemindComponent } from '../../modal/search-remind/search-remind.component';
@Component({
  selector: 'app-remind',
  templateUrl: './remind.component.html',
  styleUrls: ['./remind.component.scss'],
  providers: [RemindService]
})
export class RemindComponent implements OnInit {

  // 查询提醒人、群组modal
  @ViewChild("remindSearchRemind", { read: ViewContainerRef })
  remindSearchRemind: ViewContainerRef;
  searchRemindComponent: ComponentRef<SearchRemindComponent>;
  //发送提醒提醒信息
  public auditContentBean: any = {
    auditOpr: '',
    title: '',
    sSMSContent: '',
    sEmailContent: ''
  };
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  //短信提醒
  public sSMSFlag: any = false;
  //邮件提醒
  public sEmailFlag: any = false;
  // 传入的对象
  public item;

  public isCheckedAll: any = false;

  public listData: any = [];

  public detailData: any = [];

  public detailInfo: any = {
    nBatchno: '',
    sBeginOperator: '',
    sSendFlag: '',
    sCommitOperatorZh: '',
    sLastSendDate: ''
  }

  // 已勾选项目
  public checkProduct = [];
  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  // 提醒人展示字段
  public displayName: any;
  //查询列表getBody
  public getBody: any = {
    pageSize: 50,
    pageIndex: 1,
    sOprType: '0', //0为Nqdii，1为qdii
    nBatchno: '',//批次号
    sSendFlag: 'N',//是否有效,N为否，Y为是
    sBeginOperatorZh: '',//发起人
    sCommitOperatorZh: ''//最后审核人
  };
  constructor(
    public resolver: ComponentFactoryResolver,
    public remindService: RemindService,
    public dataService: DataService
  ) { }

  ngOnInit() {
    let that = this;
    this.loadList();
    this.defaultValue();
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        // let SessionMenuData = sessionStorage.getItem('menu');
        // this.menuData = JSON.parse(SessionMenuData)
        // this.menuResourceSet = [];
        // _.forEach(this.menuData, (item, index) => {
        //   if (item.sName == '风控管理') {
        //     _.forEach(item.children, (it, idx) => {
        //       if (it.sName == '非QDII条目管理') {
        //         _.forEach(it.children, (ite, i) => {
        //           if (ite.sName == '条目录入') {
        //             that.menuResourceSet = ite.resourceSet
        //             sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
        //           }
        //         })
        //       }
        //     })
        //   }
        // })
        this.menuResourceSet = [];
        this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '条目录入');
        sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
      }
    })
    // let SessionMenuData = sessionStorage.getItem('menu');
    // this.menuData = JSON.parse(SessionMenuData)
    // this.menuResourceSet = [];
    // _.forEach(this.menuData, (item, index) => {
    //   if (item.sName == '风控管理') {
    //     _.forEach(item.children, (it, idx) => {
    //       if (it.sName == '非QDII条目管理') {
    //         _.forEach(it.children, (ite, i) => {
    //           if (ite.sName == '条目录入') {
    //             that.menuResourceSet = ite.resourceSet
    //             sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
    //           }
    //         })
    //       }
    //     })
    //   }
    // })
    this.menuResourceSet = [];
    this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '条目录入');
    sessionStorage.setItem('btn-NQDII', this.menuResourceSet);

    this.dataService.reminderEmitter = new EventEmitter();
    this.dataService.reminderEmitter.subscribe((value) => {
      if (value) {
        this.auditContentBean.auditOpr = _.concat(value.sMbrName, value.sUsername).join(',');
        this.displayName = _.concat(value.sMbrName, value.sRealname)
        window['$']('#remindSearchRemind').modal('hide');
      }
    })
  }
  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadList();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadList(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 查看明细modal
  showViewDetail() {
    this.checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        this.checkProduct.push(item);
      }
    })
    if (this.checkProduct.length == 1) {
      this.GetSingleInfo();
      window['$']('#modal').modal('show');
    }
    else {
      window["swal"]("提示", "请选择一条记录！", "warning");
    }

  }
  // 查询单个数据的明细
  GetSingleInfo() {
    let that = this;
    console.log(this.checkProduct[0]);
    let nBatchNo = this.checkProduct[0].nBatchno;
    let getBody: any = {
      pageIndex: 0,
      pageSize: 0
    }
    this.remindService.detail(getBody, nBatchNo).subscribe(data => {
      if (data) {
        this.detailData = data.list
        console.log(data);
        this.detailInfo = this.checkProduct[0];
        // this.listData = data.list;
      }
    });
  }

  // 提醒列表
  loadList(pageNum?, pageSize?) {
    let that = this;
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.remindService.list(this.getBody).subscribe((data) => {
      if (data) {
        console.log(data);
        this.listData = data.list;
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
      }
    })

  }
  //查询提醒人列表
  showSearchRemind() {
    // 判断组件是否已创建，如果创建先注销
    if (this.searchRemindComponent && this.searchRemindComponent.instance) {
      this.searchRemindComponent.destroy();
    }
    // 动态创建组件的实例
    const searchRemindComponent = this.resolver.resolveComponentFactory(SearchRemindComponent);
    this.searchRemindComponent = this.remindSearchRemind.createComponent(searchRemindComponent);
    window['$']('#remindSearchRemind').modal('show');
  }
  //打开发送提醒modal
  showSendRemind() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        checkedItem.push(item);
      }
    });
    if (checkedItem.length == 1) {
      // let list: any = [];
      // _.forEach(checkedItem, it => {
      //   list.push(it.nBatchno);
      // })
      // let repeatList = _.uniq(list);
      // if (repeatList.length > 1) {
      //   window['swal']("提示", "请不要进行跨批次操作", "warning")
      // } else {
      this.defaultValue();
      // 用于获取批次内的文件名称展示在信息提醒、短信提醒
      let getBody: any = {
        pageIndex: 0,
        pageSize: 0
      }
      let sFileNames = [];
      let sFileNamesList = [];
      new Promise((resolve, reject) => {
        this.remindService.detail(getBody, checkedItem[0].nBatchno).subscribe(data => {
          if (data) {
            _.forEach(data.list, item => {
              sFileNames.push(item.sFileName + "、");
              sFileNamesList.push(item.sFileName + "\n");
            })
            resolve(data);
          }
        })
      }).then(data => {
        this.auditContentBean.sSMSContent = "您好：以下非QDII的条目已更新[ " + sFileNames + "]";
        this.auditContentBean.sEmailContent =
          "您好：\n" +
          "以下非QDII的条目已更新 \n" +
          sFileNamesList + "\n" +
          "请查阅！";
        window['$']('#sendRemind').modal('show');
      })
    } else {
      window['swal']("提示", "请选择一条或多条记录!", "warning");
        //   window['swal']("成功", "请选择数据进行发送提醒", "warning");
    }
  }
  //关闭modal
  hideModal() {
    window['$']('#sendRemind').modal('hide');
  }
  //NQDII/QDII提醒列表-发送提醒
  sendRemind() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        delete item.isChecked;
        let it: any = {};
        it['sSendFlag'] = item.sSendFlag;
        it['nBatchno'] = item.nBatchno;
        it['sCommitOperator'] = item.sCommitOperator;
        it['sShTime'] = item.sShTime;
        it['sShDate'] = item.sShDate;
        it['sOprType'] = 0;
        it['sBeginOperator'] = item.sBeginOperator;
        it['nLastMsgBatchno'] = item.nLastMsgBatchno;
        it['sLastSendTime'] = item.sLastSendTime;
        it['sLastSendDate'] = item.sLastSendDate;
        checkedItem.push(it);
      }
    });
    let postBody: any = {
      auditContentBean: this.auditContentBean,
      pmsSendHisList: checkedItem
    }
    console.log(postBody)
    if (this.displayName != '' && this.displayName != null && this.displayName != undefined) {
      if (!that.sSMSFlag && !that.sEmailFlag) {
        window['swal']("提示", "请选择发送提醒方式", "warning");
      } else {
        that.remindService.sendRemind(postBody).subscribe(data => {
          if (data) {
            window['$']('#sendRemind').modal('hide');
            that.loadList();
            window['swal']("成功", "提醒信息已发送", "success");
          }
        })
      }
    } else {
      window['swal']("提示", "请选择提醒人", "warning");
    }
  }
  //获取默认模板接口
  defaultValue() {
    let that = this;
    let getBody: any = {
      "sButtonId": '7009@send_history_btn_sepSend'
    }
    this.remindService.defaultValue(getBody).subscribe(data => {
      if (data) {
        console.log(data);
        if (Array.isArray(data)) {
          if (data.length > 1) {
            that.displayName = data[0].sContentZh;
            that.auditContentBean.auditOpr = data[0].sContent;
            if (data[0].sSMSFlag == 'true') {
              that.sSMSFlag = true;
            }
            if (data[0].sEmailFlag == 'true') {
              that.sEmailFlag = true;
            }
            // that.auditContentBean.sSMSContent = data[1].sContent;
            // that.auditContentBean.sEmailContent = data[1].sContent;
            that.auditContentBean.title = data[1].sRemindTitle;
          }
        }
      }
    })
  }
  //设置默认接口
  setDefault() {
    let that = this;
    let postBody = _.cloneDeep(this.auditContentBean);
    postBody['sButtonId'] = '7009@send_history_btn_sepSend';
    postBody['sEmailFlag'] = _.cloneDeep(this.sEmailFlag);
    postBody['sSMSFlag'] = _.cloneDeep(this.sSMSFlag);
    if (postBody.sEmailFlag) {
      postBody.sEmailFlag = 'Y'
    } else {
      postBody.sEmailFlag = 'N'
    }
    if (postBody.sSMSFlag) {
      postBody.sSMSFlag = 'Y'
    } else {
      postBody.sSMSFlag = 'N'
    }
    console.log(postBody)
    window['swal']({
      type: "warning",
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      showLoaderOnConfirm: true,
      title: "提示",
      text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否设置默认" + "</div>",
      html: true
    },
      function (isConfirm) {
        if (isConfirm) {
          that.remindService.setDefault(postBody).subscribe(data => {
            if (data) {
              window['swal']("提示", "设置默认成功", "success");
            }

          })
        }
      });
    console.log(postBody)
  }
}